<template>
  <div class="cart-container">
    <div class="cart-main" v-if="cartList && cartList.length">
      <div class="cart-header">
        <div class="left-container">
          <span>
            <img src="~@/assets/icon/checked.png" alt v-if="isCheckAll" @click="onCheckAll(0)"/>
            <img src="~@/assets/icon/no_check.png" alt v-else @click="onCheckAll(1)"/>
            全选
          </span>
        </div>
        <div class="right-container" @click="onEdit">{{ isEdit ? '取消' : '编辑' }}</div>
      </div>
      <div class="cart-main-container">
        <div class="cart-item" v-for="(item, index) in cartList" :key="index" @click="detailsClick(item)">
          <div class="left-container">
            <div class="check-icon">
              <img src="~@/assets/icon/checked.png" alt v-if="item.checked === 1" @click="onCheck(index, 0, item)" />
              <img src="~@/assets/icon/no_check.png" alt v-else @click="onCheck(index, 1, item)" />
            </div>
            <div class="cover">
              <img :src="imgUrl + item.indexpic" alt />
            </div>
          </div>
          <div class="right-container">
            <div class="title">{{ item.title }}</div>
            <div class="specnames">{{ item.specnames }}</div>
            <div class="price">${{ item.price }}</div>
            <div class="num" @click.stop="numChange1">
              <van-stepper 
                v-model="item.num" 
                integer 
                :name="JSON.stringify({
                  goodId: item.goodId,
                  cartId: item.id,
                  specification: item.specification
                })" 
                @change="numChange"
              />
            </div>
            <div class="del-icon" v-if="isEdit" @click="onDel(index, item)">
              <img src="~@/assets/icon/del.png" alt="">
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-submit-bar
      :price="countPrice"
      button-text="结算"
      currency="$"
      @submit="onSubmit"
      class="submit"
      v-if="cartList && cartList.length"
    />
    <div class="no-cart-container" v-else>
      <div class="tip1">购物车是空哒！</div>
      <div class="tip2">有很多宝物哦！快收藏几件喜欢的吧~</div>
      <div class="btn" @click="goHome">去逛逛</div>
    </div>
  </div>
</template>

<script>
import { Cache } from '@utils'

export default {
  data() {
    return {
      isEdit: false
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.userData;
    },
    cartList() {
      return this.$store.state.cartList;
    },
    imgUrl() {
      return this.$imgUrl;
    },
    countPrice () {
      let num = 0
      this.cartList.forEach(item => {
        num += item.num * item.price
      })
      return num * 100
    },
    isCheckAll () {
      let or = true
      this.cartList.forEach(item => {
        item.checked !== 1 && (or = false)
      })
      return or
    }
  },
  created() {
    if (!this.userInfo) {
      this.$router.push("/login");
    }
  },
  methods: {
    onDel (index, item) {
      this.$dialog.confirm({
        title: "温馨提示",
        message: `是否将${item.title}移除购物车`,
        beforeClose: async (action, done) => {
          if (action === 'cancel') {
            done()
            return
          }
          const result = await this.$fetchGet('/home/cart/del', {
            productid: item.goodId,
            specification: item.specification,
            id: item.id
          })
          if (!result.success) {
            this.$toast(result.msg)
            done()
            return
          }
          this.$toast('移除成功')
          this.cartList.splice(index, 1)
          done()
        }
      }).then(() => {

      }).catch(() => {})
    },
    onEdit () {
      this.isEdit = !this.isEdit
    },
    async onCheck (index, e, item) {
      const res = await this.$fetchGet('/home/cart/checked', {
        productid: item.goodId,
        id: item.id,
        specification: item.specification,
        checked: e
      })
      if (!res.success) {
        this.$toast(res.msg)
        return
      }
      this.cartList[index].checked = e
    },
    async onCheckAll (e) {
      const res = await this.$fetchGet('/home/cart/check', {
        checked: e
      })
      if (!res.success) {
        this.$toast(res.msg)
        return
      }
      this.cartList.map(item => {
        item.checked = e
      })
    },
    numChange1 () {},
    async numChange (value, detail) {
      console.log(value, detail)
      const data = JSON.parse(detail.name) 
      const result = await this.$fetchPost('/home/cart/editnum', {
        productid: data.goodId,
        id: data.cartId,
        specification: data.specification,
        num: value
      })
      if (!result.success) {
        this.$toast(result.msg)
        return
      }
    },
    goHome() {
      this.$router.push("/");
    },
    async onSubmit () {
      const arr = this.cartList.filter(item => item.checked)
      if (!arr.length) {
        this.$toast('请选择要结算的商品')
        return
      }
      const res = await this.$fetchGet('/home/settle/confirm')
      Cache.set('buyShoppingData', arr.map(item => {
        return {
          name: item.title,
          price: item.price,
          picture: this.imgUrl + item.indexpic,
          num: item.num
        }
      }))
      this.$router.push({
        path: '/payOrder',
        query: {
          type: 'cart'
        }
      })
    },
    detailsClick (item) {
      // protype   0普通商品，1拼团，2积分，3抢购
      let obj = {
        0: "new", // 搜索
        1: "figview", // 国际拼团
        3: "actview" // 限时抢购
      };
      this.$router.push({
        path: '/shopping/details',
        query: {
          type: obj[item.protype],
          id: item.goodId
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.cart-container {
  background: #fafafa;
  height: calc(100vh - 100px);
  position: relative;
  overflow-y: auto;
  .cart-main {
    .cart-header {
      display: flex;
      line-height: 100px;
      padding: 0 50px;
      border-bottom: 1px solid #ebebeb;
      .left-container {
        flex: 1;
        span {
          font-size: 30px;
          display: inline-block;
          color: #606060;
          img {
            vertical-align: middle;
            width: 50px;
            height: 50px;
            margin-right: 10px;
          }
        }
      }
      .right-container {
        font-size: 30px;
        color: #9f9f9f;
      }
    }
    .cart-main-container {
      .cart-item {
        display: flex;
        padding: 30px 20px;
        border-bottom: 1PX solid #DDDDDD;
        background: #fff;
        .left-container {
          display: flex;
          .check-icon {
            line-height: 200px;
            margin-right: 30px;
            img {
              width: 50px;
              height: 50px;
            }
          }
          .cover {
            img {
              width: 200px;
              height: 200px;
            }
          }
        }
        .right-container {
          display: flex;
          flex: 1;
          flex-direction: column;
          margin-left: 30px;
          position: relative;
          .title {
            font-size: 30px;
            padding-right: 50px;
          }
          .specnames {
            margin-top: 20px;
            font-size: 25px;
          }
          .price {
            margin-top: 20px;
            font-size: 25px;
            color: #FF3B3B;
          }
          .num {
            flex: 1;
            position: relative;
            margin-top: 20px;
            .van-stepper {
              position: absolute;
              bottom: 0;
              right: 0;
            }
          }
          .del-icon {
            position: absolute;
            right: 0;
            top: 0;
            img {
              width: 50px;
              height: 50px;
            }
          }
        }
      }
    }
  }
  .submit {
    bottom: 100px;
    background: #fff;
    border-bottom: 1PX solid #DDDDDD;
    .van-submit-bar__bar {
      background: #fff;
      padding: 0;
    }
  }
  .no-cart-container {
    margin-top: 30vh;
    text-align: center;
    .tip1 {
      color: #5a5a5a;
      font-size: 30px;
      margin-bottom: 20px;
    }
    .tip2 {
      color: #5a5a5a;
      font-size: 25px;
      margin-bottom: 20px;
    }
    .btn {
      width: 200px;
      height: 70px;
      font-weight: 500;
      color: #fff;
      font-size: 30px;
      margin: 0 auto;
      line-height: 70px;
      background: linear-gradient(to right, #fc8f04, #f71c19);
      border-radius: 50px;
    }
  }
}
</style>